package com.dyzx.hbb.modules.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dyzx.hbb.common.base.PageQuery;
import com.dyzx.hbb.common.base.PageResult;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseController;
import com.dyzx.hbb.common.controller.BaseCustomController;
import com.dyzx.hbb.common.controller.BaseCustomListController;
import com.dyzx.hbb.common.utils.DateFormat;
import com.dyzx.hbb.modules.sys.entity.SysDept;
import com.dyzx.hbb.modules.sys.entity.SysNotice;
import com.dyzx.hbb.modules.sys.entity.SysOrder;
import com.dyzx.hbb.modules.sys.query.NoticeMiniQuery;
import com.dyzx.hbb.modules.sys.query.NoticeQuery;
import com.dyzx.hbb.modules.sys.service.SysNoticeReadService;
import com.dyzx.hbb.modules.sys.service.SysNoticeService;

import com.dyzx.hbb.modules.sys.vo.NoticeUVO;
import com.dyzx.hbb.modules.sys.vo.NoticeVO;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RequestMapping("/sys/notice")
@RestController
@Tag(name = "14.通知管理", description = "通知相关接口")
public class NoticeController
      extends BaseCustomListController<SysNoticeService, SysNotice, NoticeQuery>
{

    @Autowired
    private SysNoticeService service;

    @Autowired
    private SysNoticeReadService readService;


    @Override
    protected SysNoticeService getBaseService() {
        return service;
    }





    @Operation(summary = "根据ID查询")
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getById(@PathVariable Long id) {
        if (id == null) {
            return Result.error("id不能为空");
        }
        Long organId = SecurityContextHolder.getOrganId();
        Long userId = SecurityContextHolder.getUserId();
        MyLambdaQueryWrapper<SysNotice> objectQueryWrapper = queryInfoWrapper();
        objectQueryWrapper.select(SysNotice::getId, SysNotice::getTitle, SysNotice::getCategory, SysNotice::getContent, SysNotice::getRecipientRange, SysNotice::getCreateDate, SysNotice::getUpdateDate, SysNotice::getStatus, SysNotice::getOperatorId, SysNotice::getOrganId, SysNotice::getRecipientId);



        objectQueryWrapper.apply("organ_id = {0}", organId);


        objectQueryWrapper.userNameSql("operator_id").as("operator_name");




        objectQueryWrapper.select("create_date");


        objectQueryWrapper.select("update_date");



        objectQueryWrapper.select("status");;
        objectQueryWrapper.select("IF(recipient_range = 1, '全部用户',IF(sys_notice.recipient_range = 2, (SELECT GROUP_CONCAT(name SEPARATOR ',') FROM sys_organ WHERE FIND_IN_SET(id, recipient_id)),IF(recipient_range = 3, (SELECT GROUP_CONCAT(name SEPARATOR ',') FROM sys_dept WHERE FIND_IN_SET(id, recipient_id)),IF(recipient_range = 4,(SELECT GROUP_CONCAT(name SEPARATOR ',') FROM sys_user WHERE FIND_IN_SET( id,recipient_id)), ''))))").as("recipient_name");

        Map<String, Object> map = service.getMap(objectQueryWrapper.apply("id={0}", id).last("limit 1"));
        if(map == null){
            return Result.error(404,"数据不存在");
        }else {
            readService.readNotice(id,userId);
        }
        return Result.ok(map);
    }


@Override
    protected MyLambdaQueryWrapper<SysNotice> queryWrapper(NoticeQuery query) {
        MyLambdaQueryWrapper<SysNotice> wrapper = new MyLambdaQueryWrapper<>();
        wrapper.select(SysNotice::getId, SysNotice::getTitle, SysNotice::getCategory,  SysNotice::getStatus,
                SysNotice::getCreateDate, SysNotice::getUpdateDate,  SysNotice::getContent, SysNotice::getOperatorId)
                .userName(SysNotice::getOperatorId).as("operator_name").organName(SysNotice::getOrganId).as("organ_name");

        if (query != null) {

            wrapper.like(StringUtils.isNotBlank(query.getTitle()), SysNotice::getTitle, query.getTitle())
                    .inSet(StringUtils.isNotBlank(query.getStatus()), SysNotice::getStatus, query.getStatus())
                    .inSet(StringUtils.isNotBlank(query.getCategory()), SysNotice::getCategory, query.getCategory())
                    .dateBetween(StringUtils.isNotBlank(query.getCreateDate()), SysNotice::getCreateDate, DateFormat.DATE, query.getCreateDate())
                    .inSet(StringUtils.isNotBlank(query.getRecipientRange()), SysNotice::getRecipientRange, query.getRecipientRange());

        }
        return wrapper;

    }



  
    protected MyLambdaQueryWrapper<SysNotice> queryInfoWrapper() {
        MyLambdaQueryWrapper<SysNotice> wrapper = new MyLambdaQueryWrapper<>();
        wrapper.select(SysNotice::getId, SysNotice::getTitle, SysNotice::getCategory,  SysNotice::getStatus,
                SysNotice::getContent,
                SysNotice::getRecipientRange,
                SysNotice::getCreateDate, SysNotice::getUpdateDate, SysNotice::getOperatorId, SysNotice::getRecipientId,SysNotice::getRecipientRange).userName(SysNotice::getOperatorId).as("operator_name").organName(SysNotice::getOrganId).as("organ_name");

        return wrapper;
    }

    /**
     * 新增
     */
    @Operation(summary = "新增")
    @PostMapping
    public Result<Boolean> save(@RequestBody NoticeVO entity)  {
        if (entity == null) {
            return Result.error("参数不能为空");
        }

        SysNotice entityCopy = new SysNotice();
        if (entityCopy == null) {
            return Result.error("创建实体对象失败");
        }
        BeanUtil.copyProperties(entity,entityCopy);

entityCopy.setOrganId(SecurityContextHolder.getOrganId());
entityCopy.setOperatorId(SecurityContextHolder.getUserId());

        boolean save =service.sendNotice(entityCopy);
        if(save){
            service.sendNotice(entityCopy);
        }
        return save? Result.ok() :Result.error("保存失败");
    }

    /**
     * 修改
     */
    @Operation(summary = "修改")
    @PutMapping
    public Result<Boolean> update(@RequestBody NoticeUVO entity) {
        if (entity == null) {
            return Result.error("参数不能为空");
        }

        SysNotice entityCopy = service.getById(entity.getId());
        if (entityCopy == null) {
            return Result.error("创建实体对象失败");
        }

        BeanUtils.copyProperties(entityCopy,entity);



        boolean data = service.updateById(entityCopy);

        return data? Result.ok() :Result.error("更新失败");
    }

    /**
     * 删除
     */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        if (id == null) {
            return Result.error("id不能为空");
        }
        Long organId = SecurityContextHolder.getOrganId();
        QueryWrapper<SysNotice> queryWrapper = new QueryWrapper<>();
        SysNotice byId =  service.getOne(queryWrapper.eq("id", id).eq("organ_id",organId).last("limit 1"));
        if (byId == null) {
            return Result.error("数据不存在");
        }

        boolean data =  service.removeById(id);
        return data? Result.ok() :Result.error("删除失败");
    }

    @Operation(summary = "通知简易列表")
    @GetMapping("/mini_list")
    public PageResult<Map<String, Object>> miniList(PageQuery pageQuery, NoticeMiniQuery query) {
        Long organId = SecurityContextHolder.getOrganId();
        Long userId = SecurityContextHolder.getUserId();
        MyLambdaQueryWrapper<SysNotice> wrapper =new MyLambdaQueryWrapper<>();
        wrapper.select(SysNotice::getId, SysNotice::getTitle,SysNotice::getCategory,SysNotice::getCreateDate).userName(SysNotice::getOperatorId).as("operator_name");
        wrapper.inSql(SysNotice::getId, "select notice_id from sys_notice_read where  operator_id = "+userId);
        wrapper.select("(select flag from sys_notice_read where notice_id = sys_notice.id and operator_id = "+ userId +" LIMIT 1)").as("flag");
        if(query != null){
            wrapper.like(StringUtils.isNotBlank(query.getTitle()), SysNotice::getTitle, query.getTitle())
                    .eq(query.getCategory()!=null, SysNotice::getCategory, query.getCategory())
                    .dateBetween(StringUtils.isNotBlank(query.getCreateDate()), SysNotice::getCreateDate, DateFormat.DATE, query.getCreateDate());
            wrapper.apply(query.getFlag()!=null, "(select flag from sys_notice_read where notice_id = sys_notice.id and operator_id = "+ userId +" LIMIT 1)="+query.getFlag());
        }
        Page<Map<String, Object>> mapPage =  service.pageMaps(pageQuery.toPage(), wrapper);
        return PageResult.parsePage(mapPage);
    }
    ///sys/notice/read/list
    @Operation(summary = "已读通知列表")
    @GetMapping("/read/list/{noticeId}")
    public Result<List<SysNotice>> readList(@PathVariable Long noticeId) {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<SysNotice> wrapper =new MyLambdaQueryWrapper<>();
        wrapper.select(SysNotice::getId, SysNotice::getTitle,SysNotice::getCategory,SysNotice::getCreateDate).userName(SysNotice::getOperatorId).as("operator_name");
        Long userId = SecurityContextHolder.getUserId();
        wrapper.select("(select flag from sys_notice_read where notice_id = sys_notice.id and operator_id = "+ userId +" LIMIT 1)").as("flag");
        wrapper.inSql(SysNotice::getId, "select notice_id from sys_notice_read where   operator_id = "+userId);
        wrapper.last("limit 30");
        wrapper.eq(SysNotice::getId,noticeId);
        wrapper.orderByDesc(SysNotice::getCreateDate);
        return Result.ok( service.list(wrapper));
    }


}
